import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, DataSource } from "typeorm";
import { BasicItemEntity } from "../entities/basic-item.entity";
import { CharacterEntity } from "../entities/character.entity";
import { CharacterResourcesEntity } from "../entities/character-resources.entity";
import { CharacterInventoryEntity } from "../entities/character-inventory.entity";
import { CharacterMineralEntity } from "../entities/character-mineral.entity";
import { CharacterMedicineEntity } from "../entities/character-medicine.entity";
import { CharacterService } from "./character.service";
import { InventoryService } from "./inventory.service";

@Injectable()
export class ShopService {
  constructor(
    @InjectRepository(BasicItemEntity)
    private basicItemRepository: Repository<BasicItemEntity>,
    private characterService: CharacterService,
    private dataSource: DataSource,
    private inventoryService: InventoryService
  ) {}

  /**
   * 根据物品ID获取物品信息
   */
  async getItemById(itemId: number): Promise<BasicItemEntity | null> {
    try {
      return await this.basicItemRepository.findOne({
        where: { id: itemId, status: 1, isTreasureShop: 1 },
      });
    } catch (error) {
      console.error("获取物品信息失败:", error);
      throw error;
    }
  }

  /**
   * 根据物品类型获取物品列表
   */
  async getItemsByType(itemType: number): Promise<BasicItemEntity[]> {
    try {
      return await this.basicItemRepository.find({
        where: { status: 1, isTreasureShop: 1 },
        order: { id: "ASC" },
      });
    } catch (error) {
      console.error("根据物品类型获取物品失败:", error);
      throw error;
    }
  }

  /**
   * 获取所有上架物品
   */
  async getAllOnSaleItems(): Promise<BasicItemEntity[]> {
    try {
      return await this.basicItemRepository.find({
        where: { status: 1, isTreasureShop: 1 },
        order: { id: "ASC" },
      });
    } catch (error) {
      console.error("获取上架物品失败:", error);
      throw error;
    }
  }

  /**
   * 购买物品（金币）
   */
  async purchaseWithGold(
    characterId: number,
    itemId: number,
    count: number
  ): Promise<any> {
    // 使用事务确保金币扣减和道具添加的原子性
    const queryRunner = this.dataSource.createQueryRunner();

    try {
      // 开始事务
      await queryRunner.connect();
      await queryRunner.startTransaction();

      // 获取物品信息
      const item = await queryRunner.manager.findOne(BasicItemEntity, {
        where: [
          { id: itemId, status: 1, isTreasureShop: 1 },
          { id: itemId, status: 1, isExpShop: 1 },
        ],
      });
      if (!item) {
        throw new Error("物品不存在或未上架");
      }

      // 检查角色是否存在
      const character = await queryRunner.manager.findOne(CharacterEntity, {
        where: { id: characterId },
      });
      if (!character) {
        throw new Error("角色不存在");
      }

      if (count <= 0) {
        throw new Error("购买数量必须大于0");
      }

      if (item.goldPrice <= 0) {
        throw new Error("价格售价错误，请联系客服");
      }

      // 计算总价格
      const totalPrice = item.goldPrice * count;

      // 检查金币余额
      const resources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId },
        }
      );
      if (!resources) {
        throw new Error("角色资源信息不存在");
      }

      if (resources.gold < totalPrice) {
        throw new Error("金币不足");
      }

      // 扣除金币
      await queryRunner.manager.update(
        CharacterResourcesEntity,
        { characterId },
        { gold: resources.gold - totalPrice }
      );

      // 根据分类入不同背包：category 6→矿石背包；category 1→药品背包；其他→杂物背包
      if (item.category === 6) {
        const existingMineral = await queryRunner.manager.findOne(
          CharacterMineralEntity,
          { where: { characterId, itemId: item.id, status: 1 } }
        );
        if (existingMineral) {
          await queryRunner.manager.update(
            CharacterMineralEntity,
            { id: existingMineral.id },
            { num: existingMineral.num + count, updated_at: new Date() }
          );
        } else {
          await queryRunner.manager.insert(CharacterMineralEntity, {
            characterId,
            itemId: item.id,
            num: count,
            status: 1,
            created_at: new Date(),
            updated_at: new Date(),
          });
        }
      } else if (item.category === 1) {
        // 药品背包
        const existingMed = await queryRunner.manager.findOne(
          CharacterMedicineEntity,
          { where: { characterId, itemId: item.id, status: 1 } }
        );
        if (existingMed) {
          await queryRunner.manager.update(
            CharacterMedicineEntity,
            { id: existingMed.id },
            { num: existingMed.num + count, updated_at: new Date() }
          );
        } else {
          await queryRunner.manager.insert(CharacterMedicineEntity, {
            characterId,
            itemId: item.id,
            name: item.name,
            pic: item.pic,
            description: item.description,
            itemType: 1,
            num: count,
            status: 1,
            level: item.lv,
            rarity: 1,
            obtainedAt: new Date(),
            created_at: new Date(),
            updated_at: new Date(),
          });
        }
      } else {
        // 默认仍入杂物背包
        const existingItem = await queryRunner.manager.findOne(
          CharacterInventoryEntity,
          { where: { characterId, itemId: item.id } }
        );
        if (existingItem && existingItem.status === 1) {
          await queryRunner.manager.update(
            CharacterInventoryEntity,
            { id: existingItem.id },
            { num: existingItem.num + count, updated_at: new Date() }
          );
        } else if (existingItem) {
          await queryRunner.manager.update(
            CharacterInventoryEntity,
            { id: existingItem.id },
            {
              num: count,
              status: 1,
              obtainedAt: new Date(),
              updated_at: new Date(),
            }
          );
        } else {
          await queryRunner.manager.insert(CharacterInventoryEntity, {
            characterId,
            itemId: item.id,
            name: item.name,
            itemType: item.lv,
            num: count,
            status: 1,
            pic: item.pic,
            description: item.description,
            level: item.lv,
            rarity: 1,
            obtainedAt: new Date(),
            created_at: new Date(),
            updated_at: new Date(),
          });
        }
      }

      // 提交事务
      await queryRunner.commitTransaction();

      return {
        success: true,
        goods: {
          id: item.id,
          name: item.name,
          count: count,
          price: item.goldPrice,
          totalPrice: totalPrice,
        },
        message: "购买成功",
      };
    } catch (error) {
      // 回滚事务
      await queryRunner.rollbackTransaction();
      console.error("金币购买失败:", error);
      throw error;
    } finally {
      // 释放查询运行器
      await queryRunner.release();
    }
  }

  /**
   * 购买物品（银币）
   */
  async purchaseWithSilver(
    characterId: number,
    itemId: number,
    count: number,
    silverType: number = 0
  ): Promise<any> {
    // 使用事务确保银币扣减和道具添加的原子性
    const queryRunner = this.dataSource.createQueryRunner();

    try {
      // 开始事务
      await queryRunner.connect();
      await queryRunner.startTransaction();

      // 获取物品信息
      const item = await queryRunner.manager.findOne(BasicItemEntity, {
        where: { id: itemId, status: 1, isTreasureShop: 0 },
      });
      if (!item) {
        throw new Error("物品不存在或未上架");
      }

      // 检查角色是否存在
      const character = await queryRunner.manager.findOne(CharacterEntity, {
        where: { id: characterId },
      });
      if (!character) {
        throw new Error("角色不存在");
      }

      if (count <= 0) {
        throw new Error("购买数量必须大于0");
      }

      if (item.silverPrice <= 0) {
        throw new Error("价格售价错误，请联系客服");
      }

      // 计算总价格
      const totalPrice = item.silverPrice * count;

      // 检查银币余额
      const resources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId },
        }
      );
      if (!resources) {
        throw new Error("角色资源信息不存在");
      }

      // 根据silverType选择银币类型
      let availableSilver = 0;
      if (silverType === 0) {
        // 普通银币
        availableSilver = resources.silver;
      } else if (silverType === 1) {
        // 绑定银币
        availableSilver = resources.bdSilver;
      } else {
        throw new Error("无效的银币类型");
      }

      if (availableSilver < totalPrice) {
        throw new Error("银币不足");
      }

      // 扣除银币
      if (silverType === 0) {
        await queryRunner.manager.update(
          CharacterResourcesEntity,
          { characterId },
          { silver: resources.silver - totalPrice }
        );
      } else {
        await queryRunner.manager.update(
          CharacterResourcesEntity,
          { characterId },
          { bdSilver: resources.bdSilver - totalPrice }
        );
      }

      // 购买银币矿石：写入矿石背包
      const existingMineral = await queryRunner.manager.findOne(
        CharacterMineralEntity,
        { where: { characterId, itemId: item.id, status: 1 } }
      );
      if (existingMineral) {
        await queryRunner.manager.update(
          CharacterMineralEntity,
          { id: existingMineral.id },
          { num: existingMineral.num + count, updated_at: new Date() }
        );
      } else {
        await queryRunner.manager.insert(CharacterMineralEntity, {
          characterId,
          itemId: item.id,
          num: count,
          status: 1,
          created_at: new Date(),
          updated_at: new Date(),
        });
      }

      // 提交事务
      await queryRunner.commitTransaction();

      return {
        success: true,
        goods: {
          id: item.id,
          name: item.name,
          count: count,
          price: item.silverPrice,
          totalPrice: totalPrice,
          silverType: silverType,
        },
        message: "购买成功",
      };
    } catch (error) {
      // 回滚事务
      await queryRunner.rollbackTransaction();
      console.error("银币购买失败:", error);
      throw error;
    } finally {
      // 释放查询运行器
      await queryRunner.release();
    }
  }

  /**
   * 搜索物品
   */
  async searchItems(keyword: string): Promise<BasicItemEntity[]> {
    try {
      return await this.basicItemRepository
        .createQueryBuilder("item")
        .where(
          "item.status = :status AND item.isTreasureShop = :isTreasureShop",
          {
            status: 1,
            isTreasureShop: 1,
          }
        )
        .andWhere(
          "(item.name LIKE :keyword OR item.description LIKE :keyword)",
          {
            keyword: `%${keyword}%`,
          }
        )
        .orderBy("item.id", "ASC")
        .getMany();
    } catch (error) {
      console.error("搜索物品失败:", error);
      throw error;
    }
  }

  /**
   * 获取热门物品
   */
  async getHotItems(limit: number = 10): Promise<BasicItemEntity[]> {
    try {
      return await this.basicItemRepository.find({
        where: { status: 1, isTreasureShop: 1 },
        order: { id: "ASC" },
        take: limit,
      });
    } catch (error) {
      console.error("获取热门物品失败:", error);
      throw error;
    }
  }
}
